# 作业先完成，再完美
# 多进程锁, 多线程锁都要自己实现一遍
# 多进程通过Queue来实现进程通信
# 把上述概念熟记并理解
from threading import Thread
from multiprocessing import Process, Queue
from threading import Lock as Thread_Lock
from multiprocessing import Lock as Process_Lock

def save_to_file(index, file_name, lock):
    with lock:
        with open(file_name, 'a', encoding='utf-8') as f:
            f.write(str(index) + '\n')

def process_queue(index, my_queue):
    my_queue.put(index)

if __name__ == '__main__':
    # 多进程锁, 多线程锁都要自己实现一遍
    thread_list = []
    lock = Thread_Lock()
    for i in range(10):
        my_thread = Thread(target=save_to_file, args=(i, 'thread.txt', lock))
        thread_list.append(my_thread)
        my_thread.start()
    for i in thread_list:
        i.join()
    print(f'线程结束')

    process_list = []
    process_lock = Process_Lock()
    for i in range(10):
        my_process = Process(target=save_to_file, args=(i, 'process.txt', process_lock))
        process_list.append(my_process)
        my_process.start()
    for i in process_list:
        i.join()
    print(f'进程结束')

    # 多进程通过Queue来实现进程通信
    my_queue = Queue()
    process_list2 = []
    for i in range(10):
        my_process2 = Process(target=process_queue, args=(i, my_queue))
        process_list2.append(my_process2)
        my_process2.start()
    for i in process_list2:
        i.join()

    while True:
        print(f'{my_queue.get()}')